package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.services.impl.SqfwSummaryForAdminServiceImpl;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwV2.dto.publicSecurity.PublicSecurityDTO;
import com.budwk.app.sqfwV2.enums.publicSecurity.PublicSecurityFileEnum;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityExcelService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community-dev
 * @description: 大营路社会治安服务实现 （后台管理系统）
 * @author: LJT
 * @create: 2024-02-20 10:16
 **/
@IocBean(name = "DaYingLuSocietySecForAdminService")
@Slf4j
public class DaYingLuSocietySecForAdminServiceImpl extends PublicSecurityExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysLogService sysLogService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private PublicSecurityService publicSecurityService;

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("DaYingLuSocietySecForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        // 查询流程pdf
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = Collections.synchronizedList(new ArrayList<SqfwCustomForAdminCommonVO>());
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictSubInfoMaps(Arrays.asList(
                    "place_types_entertainment_venues_daying_road", "place_types_key_dining_venues_daying_road",
                    "place_types_health_service_daying_road", "place_types_health_care_daying_road",
                    "place_types_education_training_daying_road", "place_types_fraud_risks_daying_road",
                    "place_types_large_comprehensive_daying_road", "place_types_key_service_other_daying_road",
                    "dining_venues_wedding_square_daying_road", "dining_venues_large_scale_restaurant_daying_road",
                    "dining_venues_night_market_daying_road", "dining_venues_other_daying_road",
                    "health_service_hospital_daying_road", "health_service_clinic_daying_road",
                    "health_service_plastic_surgery_daying_road", "health_service_other_daying_road",
                    "health_care_beadhouse_daying_road", "health_care_sanatorium_daying_road",
                    "health_care_rhabilitation_center_daying_road", "health_care_other_daying_road",
                    "education_training_university_daying_road", "education_training_middle_school_daying_road",
                    "education_training_primary_school_daying_road", "education_training_kindergarten_daying_road",
                    "education_training_tutoring_institutions_daying_road", "education_training_training_center_daying_road",
                    "education_training_childcare_institutions_daying_road", "education_training_other_daying_road",
                    "fraud_risks_bank_daying_road", "fraud_risks_eelephone_card_daying_road",
                    "fraud_risks_professional_sales_daying_road", "fraud_risks_other_daying_road",
                    "large_comprehensive_commercial_complex_daying_road", "large_comprehensive_large_shopping_mall_daying_road",
                    "large_comprehensive_farm_product_market_daying_road", "large_comprehensive_gathering_places_daying_road",
                    "large_comprehensive_religious_facilities_daying_road", "large_comprehensive_medium_square_daying_road",
                    "large_comprehensive_other_daying_road","key_other_foot_massage_shop_daying_road",
                    "key_other_massage_parlour_daying_road", "key_other_beauty_salon_daying_road",
                    "key_other_health_club_daying_road", "key_other_gym_daying_road", "key_other_bath_centre_daying_road",
                    "key_other_hotel_daying_road", "key_other_bg_hotel_daying_road", "key_other_hostel_daying_road",
                    "key_other_other_daying_road","entertainment_venues_bar_daying_road", "entertainment_venues_ktv_daying_road",
                    "entertainment_venues_nightclub_daying_road", "entertainment_venues_internet_bar_daying_road",
                    "entertainment_venues_chess_card_club_daying_road", "entertainment_venues_script_kill_daying_road"
                    , "entertainment_venues_cinema_daying_road", "entertainment_venues_other_daying_road"));
            CompletableFuture[] cf = sqfwCustomForAdminCommonVOList.stream().map(item -> CompletableFuture.runAsync(() ->
                            processListData(item, pdfUrlMap, dictCodesMap, finalCommonVOList), taskQueryExecutor)
                    .thenApplyAsync(r -> r)).toArray(CompletableFuture[]::new);
            CompletableFuture.allOf(cf).join();

            // 避免将超时处理放在异步线程中处理，以免数据错乱
            List<SqfwCustomForAdminCommonVO> finalSqfwCustomForAdminCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            finalCommonVOList.forEach(item -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(item, target);
                if (Strings.isNotBlank(target.getCheckStatus())
                        && SqfwSummaryForAdminServiceImpl.TO_DO_CHECK_OUT.equals(target.getCheckStatus())
                        && null != target.getFillDate()) {
                    Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
                    Date thisFillDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(target.getFillDate()));
                    if (offsetDate.compareTo(thisFillDate) < 0) {
                        target.setCheckStatus(SqfwSummaryForAdminServiceImpl.CHECK_OUT);
                    }
                }
                finalSqfwCustomForAdminCommonVOList.add(target);
            });
            pagination.setList(finalSqfwCustomForAdminCommonVOList.stream().sorted(Comparator.comparing(SqfwCustomForAdminCommonVO::getFillDate, Comparator.reverseOrder())).collect(Collectors.toList()));
        }
        log.info("DaYingLuSocietySecForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormSummaryNew == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        batchDeleteDataNew(SecurityUtil.getUserId(), sqfwFormSummaryNew);
        return 0;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int batchDelete(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        // 查询数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getId, "in", ids);
        List<Sqfw_formSummary_new> newList = sqfwFormsummaryNewService.query(cnd);
        if (newList.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        if (!newList.isEmpty()) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            CompletableFuture.runAsync(() -> {
                for (Sqfw_formSummary_new sqfwFormSummaryNew : newList) {
                    batchDeleteDataNew(userId, sqfwFormSummaryNew);
                }
            }, executorService);
            executorService.shutdown();
        }
        return newList.size();
    }

    @Override
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        return 0;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            // 时间
            if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">=", communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()));
                cnd.and(Sqfw_formSummary_new::getFillDate, "<=", communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
            }
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag() == true) {
            bean.setFormSummaryNewIdList(Collections.emptyList());
        }
        return super.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), bean.getFormSummaryNewIdList());
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new GenerateWordAndPdfUrlVO();
            }
        }
        generateWordAndPdfUrlVO.setPdfUrl(generatePdfColl(bean.getFormSummaryNewIdList()));
        return generateWordAndPdfUrlVO;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCommunity())) {
            criSql.andEquals(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup placeName = Cnd.exps(new Static("param_data->>'placeName' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup address = Cnd.exps(new Static("param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operator = Cnd.exps(new Static("param_data->>'operator' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operatorTelephone = Cnd.exps(new Static("param_data->>'operatorTelephone' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup placeType = Cnd.exps(new Static("param_data->>'placeType' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            criSql.and(placeName.or(address).or(operator).or(operatorTelephone).or(placeType).or(community).or(createUserName));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);
        // 场所名称
        if (StringUtils.isNotBlank(bean.getPlaceName())) {
            criSql.andEquals("param_data->>'placeName'", bean.getPlaceName());
        }
        // 联系地址
        if (StringUtils.isNotEmpty(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 联系人
        if (StringUtils.isNotBlank(bean.getOperator())) {
            criSql.andEquals("param_data->>'operator'", bean.getOperator());
        }
        // 经营者联系电话
        if (StringUtils.isNotEmpty(bean.getOperatorTelephone())) {
            criSql.andEquals("param_data->>'operatorTelephone'", bean.getOperatorTelephone());
        }
        // 场所类型
        if (StringUtils.isNotEmpty(bean.getPlaceType())) {
            criSql.andEquals("param_data->>'placeType'", bean.getPlaceType());
        }
        // 具体分类
        if (StringUtils.isNotEmpty(bean.getMainBusinessScope())) {
            criSql.andEquals("param_data->>'mainBusinessScope'", bean.getMainBusinessScope());
        }
        // 有无涉黑涉恶
        if (StringUtils.isNotEmpty(bean.getInCrimeAndEvil())) {
            criSql.andEquals("param_data->>'InCrimeAndEvil'", bean.getInCrimeAndEvil());
        }
        // 检查人员
        if (StringUtils.isNotEmpty(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        // 检查人员电话
        if (StringUtils.isNotEmpty(bean.getCreateUserPhone())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserPhone, bean.getCreateUserPhone());
        }
        // 检查状态(超时情况： 1-超时(未检查)， 2-未超时)
        if (Strings.isNotBlank(bean.getCheckStatus())) {
            if (CommonCheckUtils.CHECK_OUT.equals(bean.getCheckStatus())) {
                // 查询未超时数据，只查询30天内的未检查数据 + 已检查数据（（check_status != 2 且 fill_date>当前时间-30天））
                Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.SDF_START.format(DateUtil.beginOfWeek(new Date())));
                SqlExpressionGroup notTimeOut = Cnd.exps(new Static("fill_date >= '" + offsetDate + "' AND check_status = '1'"));
                SqlExpressionGroup checked = Cnd.exps(new Static("check_status = '2'"));
                criSql.and(notTimeOut.or(checked));
            } else if (CommonCheckUtils.TO_DO_CHECK_OUT.equals(bean.getCheckStatus())) {
                // 查询超时数据，只查询30天前的数据（（check_status=1 且 fill_date<当前时间-30天））
                Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.SDF_START.format(DateUtil.beginOfWeek(new Date())));
                criSql.and(Sqfw_formSummary_new::getFillDate, "<", offsetDate);
                criSql.andEquals(Sqfw_formSummary_new::getCheckStatus, bean.getCheckStatus());
            } else {
                criSql.andEquals(Sqfw_formSummary_new::getCheckStatus, bean.getCheckStatus());
            }
        }
        // 是否存在隐患
        if (ObjectUtil.isNotEmpty(bean.getWhetherThereIsAnyHiddenDanger())) {
            criSql.andEquals("param_data->>'whetherThereIsAnyHiddenDanger'", bean.getWhetherThereIsAnyHiddenDanger());
        }
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<CheckDataForAdminVO>();
            }
        }
        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        Cnd cnd = Cnd.NEW();
        cnd.and("id", "in", bean.getFormSummaryNewIdList());
        cnd.and("type", "=", SqfwFormSummaryConstants.public_security);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary_new> formSummaryList = sqfwFormsummaryNewService.query(cnd);
        if (formSummaryList.isEmpty()) {
            return new ArrayList<CheckDataForAdminVO>();
        }
        for (PublicSecurityFileEnum item : PublicSecurityFileEnum.values()) {
            CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
            checkDataForAdminVO.setFileIdentity(item.getCode());
            checkDataForAdminVO.setCreateConditionFlag(true);
            checkDataForAdminVOList.add(checkDataForAdminVO);
        }
        return checkDataForAdminVOList;
    }

    @Override
    public void reGeneratePdf(String id) {
        publicSecurityService.reGeneratePDF(id);
    }

    /**
     * 生成pdf合集
     *
     * @return
     */
    private String generatePdfColl(List<String> ids) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();

        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.PUBLIC_SECURITY.getName());
        cnd.and(Sqfw_formSummary_new::getId, "in", ids);
        cnd.desc(Sqfw_formSummary_new::getFillDate);
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(cnd);
        Set<String> sqfwFlowIdSet = sqfwFormSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toSet());
        Cnd cndFlow = Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdSet);
        cndFlow.and(Sqfw_completeflow::getFileType, "like", "%" + SqfwFormSummaryConstants.public_security + "%")
                .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                .and(Sqfw_completeflow::getResourcePath, "!=", "error")
                .orderBy("create_date", "asc");
        List<Sqfw_completeflow> flwoList = sqfwCompleteflowService.query(cndFlow);
        String url = "";
        if (!flwoList.isEmpty()) {
            List<String> pdfPathList = flwoList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
            url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, DownLoadFileNameEnum.DYL_PUBLIC_SECURITY_STANDING_PDF.getName() + DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        }
        return url;
    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.DaYingLuSocietySecForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.DaYingLuSocietySecForAdminController.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }

    /**
     * 处理返回的list数据
     *
     * @param source
     * @param pdfUrlMap
     * @param dictCodesMap
     * @param finalCommonVOList
     */
    private void processListData(
            Sqfw_formSummary_new source,
            Map<String, String> pdfUrlMap,
            Map<String, String> dictCodesMap,
            List<SqfwCustomForAdminCommonVO> finalCommonVOList) {
        SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
        BeanUtil.copyProperties(source, target);
        target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
        PublicSecurityDTO FireSafetyDTO = JSONObject.parseObject(target.getParamData(), PublicSecurityDTO.class);
        if (ObjectUtil.isNotEmpty(FireSafetyDTO)) {
            String mainBusinessScope = FireSafetyDTO.getMainBusinessScope();
            if (StringUtils.isNotEmpty(mainBusinessScope)) {
                List<String> mainBusinessScopes = Arrays.asList(mainBusinessScope.split(","));
                StringBuffer sb = new StringBuffer();
                mainBusinessScopes.forEach(mainBusiness -> {
                    String finalMainBusiness = dictCodesMap.get(mainBusiness);
                    if (StringUtils.isNotEmpty(finalMainBusiness)) {
                        sb.append(finalMainBusiness).append(",");
                    } else {
                        sb.append(mainBusiness).append(",");
                    }
                });
                target.setMainBusinessScopeName(sb.substring(0, sb.length() - 1));
            }
            String placeType = FireSafetyDTO.getPlaceType();
            if (StringUtils.isNotEmpty(placeType)) {
                List<String> placeTypes = Arrays.asList(placeType.split(","));
                StringBuffer sb = new StringBuffer();
                placeTypes.forEach(item -> {
                    String finalMainBusiness = dictCodesMap.get(item);
                    if (StringUtils.isNotEmpty(finalMainBusiness)) {
                        sb.append(finalMainBusiness).append(",");
                    } else {
                        sb.append(item).append(",");
                    }
                });
                target.setPlaceType(sb.substring(0, sb.length() - 1));
            }
        }
        finalCommonVOList.add(target);
    }
}
